//
//  MYShopDetailsSpecificationsSelectView.m
//  MuYing
//
//  Created by tbb on 2019/7/29.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYShopDetailsSpecificationsSelectView.h"
#import "MYShopDetailsSpecificationsSelectHeaderView.h"
#import "MYShopDetailsSpecificationsCell.h"
#define BGVIEW_H (kYQPScreenHeight * (524/667.0))
#define BGVIEW_TOP (kYQPScreenHeight - BGVIEW_H)
@interface MYShopDetailsSpecificationsSelectView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView * specificationsCollView;

@property (nonatomic, copy) SpecificationsCancelBlack cancelBlack;
@property (nonatomic, copy) SpecificationsResultBlack resultBlack;
@property (nonatomic, copy) UpdateGoodsInfoResultBlack updateGoodsInofBlack;
@property (nonatomic, strong) MYShopDetailsSpecificationsSelectHeaderView * goodsHeaderView;
@property (nonatomic, strong) UIView * bgView;
@property (nonatomic, strong) MYShopDetailsSpecificationsSelectBottonBtn * bottonView;

/// 销售预选择的属性
@property (strong, nonatomic) NSMutableArray *attrValueIds;
/// 销售最终选择的属性
@property (strong, nonatomic) NSMutableArray *attrSelectValueIds;
/// 当前选中的indexPath
@property (strong, nonatomic) NSIndexPath *indexPath;

/// 根据销售属性选出的商品model
@property (strong, nonatomic) YQPSpuSaleAttrValueListModel *selectedModel;

@property (strong, nonatomic) YQPGoodInfoModel *infoModel;

@end

@implementation MYShopDetailsSpecificationsSelectView
+ (void)showShopSearchScreenViewWithModel:(YQPSkuInfoModel *)model andAttr:(NSArray *)attrArr ResultBlack
:(SpecificationsResultBlack)resultBlack updateGoodsInfoBlack:(UpdateGoodsInfoResultBlack)updateGoodsInfoBlack
cancelBlack:(SpecificationsCancelBlack)cancelBlack {
    MYShopDetailsSpecificationsSelectView *screenView = [[MYShopDetailsSpecificationsSelectView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    screenView.backgroundColor = HexColorA(0x000000, 0.2);//HexColor(0xF3F5F9);
    screenView.resultBlack = resultBlack;
    screenView.cancelBlack = cancelBlack;
    screenView.updateGoodsInofBlack = updateGoodsInfoBlack;
    screenView.attrArr = attrArr;
    [screenView showSelctTableView];
    screenView.model = model;
}

 - (void)setModel:(YQPSkuInfoModel *)model
{
    _model = model;
    self.goodsHeaderView.priceLb.text = [NSString stringWithFormat:@"$%.2f",model.price.doubleValue];
    self.goodsHeaderView.inventoryLb.text = [NSString stringWithFormat:@"%@%@%@",kYQLS(@"库存"),(model.inventory ? model.inventory : @"0"),kYQLS(@"件")];
    //YQPSkuImageListModel *imageModel = model.skuDefaultImg;
    [self.goodsHeaderView.goodsIcon sd_setImageWithURL:[NSURL URLWithString:model.skuDefaultImg] placeholderImage:IMAGE_NAMED(@"")];
//    [self querySalesGoodAttrApi];

}

#pragma mark - 根据选中的销售属性匹配对应的商品
- (void)querySalesGoodAttrApi
{
    [self.attrSelectValueIds removeAllObjects];
    NSMutableArray *specificationsArr = [NSMutableArray array];
    for (int i = 0; i < self.attrArray.count; i++) {
        YQPSpuSaleAttrListCheckBySkuModel *model = self.attrArray[i];
        for (YQPSpuSaleAttrValueListModel *attrModel in model.spuSaleAttrValueList) {
                if (attrModel.isChecked) {
                    [self.attrSelectValueIds addObject:attrModel.ID];
                    [specificationsArr addObject:attrModel.saleAttrValueName];
                }
        }
    }
    
    if (self.attrSelectValueIds.count < self.attrArray.count) {
        return;
    }
    
    if (specificationsArr.count > 1) {
        NSString *specificationsStr = [specificationsArr componentsJoinedByString:@","];
        self.goodsHeaderView.specificationsLb.text = specificationsStr;
    }else{
        self.goodsHeaderView.specificationsLb.text = kYQLS(@"请选择规格");
    }
    
    MYShopDetailsSpecificationsAddCountCell *cell = [self.specificationsCollView dequeueReusableCellWithReuseIdentifier:@"MYShopDetailsSpecificationsAddCountCell" forIndexPath:[NSIndexPath indexPathForItem:0 inSection:self.attrArray.count]];

    NSSet *set = [NSSet setWithArray:self.attrSelectValueIds];
    NSMutableArray *seleArr = NSMutableArray.array;
    [seleArr addObjectsFromArray:(NSArray *)set];
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendGetRequest:kGET_GOOD_ATTRVALUE_MATCH_SKU_URL parameters:@{@"attrValueIds":[seleArr componentsJoinedByString:@","]} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code==0) {
            YQPSpuSaleAttrValueListModel *model = YQPSpuSaleAttrValueListModel.new;
            model.ID = responseObject.data[@"skuId"];
            model.buyNumber = cell.numTextFiled.text;
            model.price = responseObject.data[@"price"];
            self.selectedModel = model;
            [self getGoodsInfoSkuid:self.selectedModel.ID];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
        YQHIDELOADINGTIPS
    }];
}

-(void)getGoodsInfoSkuid:(NSString *)skuId {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kGET_GOOD_INFO_URL,skuId];
    [YQPNetWorkingManager sendGetRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        self.infoModel = [YQPGoodInfoModel mj_objectWithKeyValues:responseObject.data];
        self.model = self.infoModel.skuInfo;
        [self.specificationsCollView reloadData];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
    }];
}

- (void)setAttrArr:(NSArray *)attrArr
{
    _attrArr = attrArr;
    [self.attrArray removeAllObjects];
    [self.attrArray addObjectsFromArray:self.attrArr];
    
    NSMutableArray *specificationsArr = [NSMutableArray array];
    for (YQPSpuSaleAttrListCheckBySkuModel *model in self.attrArray) {
        for (YQPSpuSaleAttrValueListModel *attrModel in model.spuSaleAttrValueList) {
                if (attrModel.isChecked) {
                    [specificationsArr addObject:attrModel.saleAttrValueName];
                }
        }
    }
    
    if (specificationsArr.count > 0) {
        NSString *specificationsStr = [specificationsArr componentsJoinedByString:@","];
        self.goodsHeaderView.specificationsLb.text = specificationsStr;
    }else{
        self.goodsHeaderView.specificationsLb.text = kYQLS(@"请选择规格");
    }

    [self.specificationsCollView reloadData];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.attrArray = NSMutableArray.new;
        self.attrValueIds = NSMutableArray.array;
        self.attrSelectValueIds = NSMutableArray.array;
        [self addSubview:self.specificationsCollView];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

-(void)showSelctTableView {
    //1. 获取当前应用的主窗口
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
    // 浮现动画
    [UIView animateWithDuration:0.3 animations:^{
        //self.selectTableView.left = (kYQPScreenWidth-selectTableViewW);
        self.bgView.top = BGVIEW_TOP-kHeight_Botton_SafeArea;
    }];
    
}

-(void)cancelSelctTableView {
//    if (self.attrSelectValueIds.count < self.attrArray.count) {
//        [MBProgressHUD showMessage:@"请完善属性选择"];
//        return;
//    }
    if (self.cancelBlack) {
        self.cancelBlack();
    }
    
    // 关闭动画
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.top = kYQPScreenHeight + BGVIEW_H;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.selectTableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.selectTableView.contentInset = UIEdgeInsetsZero;
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.attrArray.count + 1;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == self.attrArray.count) {
        return 1;
    }
    YQPSpuSaleAttrListCheckBySkuModel *model = self.attrArray[section];

    return [model.spuSaleAttrValueList count];
    
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == self.attrArray.count) {
        MYShopDetailsSpecificationsAddCountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShopDetailsSpecificationsAddCountCell" forIndexPath:indexPath];
        return cell;
        
    }
    YQPSpuSaleAttrListCheckBySkuModel *model = self.attrArray[indexPath.section];
    YQPSpuSaleAttrValueListModel *attrModel = model.spuSaleAttrValueList[indexPath.row];
    MYShopDetailsSpecificationsCollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShopDetailsSpecificationsCollCell" forIndexPath:indexPath];
    [cell setModel:attrModel];
    return cell;
}

//设置头视图的尺寸，如果想要使用头视图，则必须实现该方法
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{

    if (section == 0) {
        return CGSizeMake(kScreenWidth, 32);
    }else if (section == self.attrArray.count) {
        return CGSizeMake(kScreenWidth,64);
    }
    else{
        return CGSizeMake(kScreenWidth,64);
    }

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == self.attrArray.count) {
        return CGSizeMake(kScreenWidth,28);
    }

    return CGSizeMake(61,28);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == self.attrArray.count) {
        MYShopDetailsSpecificationsTitleHeader *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MYShopDetailsSpecificationsTitleHeaer" forIndexPath:indexPath];
        view.titleLb.text = @"";
        return view;
    }
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        MYShopDetailsSpecificationsTitleHeader *head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MYShopDetailsSpecificationsTitleHeaer" forIndexPath:indexPath];
            
        YQPSpuSaleAttrListCheckBySkuModel *model = self.attrArray[indexPath.section];

        head.titleLb.text = model.saleAttrName;

        return head;
    }
    return nil;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 18.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 12;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    YQPSpuSaleAttrListCheckBySkuModel *model = nil;
    if (indexPath.section < self.attrArray.count) {
        model = self.attrArray[indexPath.section];
    }
    YQPSpuSaleAttrValueListModel *attrModel = nil;
    if (indexPath.row < model.spuSaleAttrValueList.count) {
        attrModel = model.spuSaleAttrValueList[indexPath.row];
    }

    for (YQPSpuSaleAttrValueListModel *listModel in model.spuSaleAttrValueList) {
        if ([listModel.ID isEqualToString:attrModel.ID]) {
            listModel.isChecked = YES;
        }else{
            listModel.isChecked = NO;
        }
    }
    //筛选商品
    [self querySalesGoodAttrApi];
    [self.specificationsCollView reloadData];

}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{

}


- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;

}


#pragma mark -- lazy
-(UICollectionView *)specificationsCollView {
    if (!_specificationsCollView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 12;
        _specificationsCollView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _specificationsCollView.backgroundColor =  UIColor.whiteColor;
        _specificationsCollView.delegate = self;
        _specificationsCollView.dataSource = self;
        _specificationsCollView.bounces = false;
        _specificationsCollView.contentInset = UIEdgeInsetsMake(0, 12, 0, 12);
        //实现多选必须实现这个方法,默认为NO
        _specificationsCollView.allowsMultipleSelection = YES;
    }
    return _specificationsCollView;
}

-(UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, kYQPScreenHeight + BGVIEW_H, kYQPScreenWidth, BGVIEW_H)];
        _bgView.backgroundColor = UIColor.whiteColor;
        [UIView roundedSetView:_bgView cornerRadius:12 Type:(kRoundedSetViewTypeTRL)];
        [self addSubview:_bgView];
        [_bgView addSubview:self.goodsHeaderView];
        
        [_bgView addSubview:self.bottonView];
        [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(49);
        }];
        
        [self.specificationsCollView registerClass:MYShopDetailsSpecificationsTitleHeader.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MYShopDetailsSpecificationsTitleHeaer"];
        
        [self.specificationsCollView registerNib:[UINib nibWithNibName:@"MYShopDetailsSpecificationsAddCountCell" bundle:nil] forCellWithReuseIdentifier:@"MYShopDetailsSpecificationsAddCountCell"];
        [self.specificationsCollView registerNib:[UINib nibWithNibName:@"MYShopDetailsSpecificationsCollCell" bundle:nil] forCellWithReuseIdentifier:@"MYShopDetailsSpecificationsCollCell"];
        [_bgView addSubview:self.specificationsCollView];
        [self.specificationsCollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.goodsHeaderView.mas_bottom).mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.bottonView.mas_top).mas_equalTo(0);
        }];
    }
    return _bgView;
}

-(MYShopDetailsSpecificationsSelectHeaderView *)goodsHeaderView {
    if (!_goodsHeaderView) {
        _goodsHeaderView = [[MYShopDetailsSpecificationsSelectHeaderView alloc] initWithFrame:CGRectMake(0, 0, kYQPScreenWidth, 115)];
        _goodsHeaderView.priceLb.text = @"HKD0.00";
        _goodsHeaderView.inventoryLb.text = [NSString stringWithFormat:@"%@0%@",kYQLS(@"库存"),kYQLS(@"件")];
        _goodsHeaderView.specificationsLb.text = kYQLS(@"请选择容量大小");
    }
    return _goodsHeaderView;
}

-(MYShopDetailsSpecificationsSelectBottonBtn *)bottonView {
    if (!_bottonView) {
        _bottonView = [MYShopDetailsSpecificationsSelectBottonBtn viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        ws(self);

        [_bottonView.determineBtn addTapAction:^(id  _Nonnull sender) {
            if (weakself.resultBlack) {
                if (weakself.selectedModel) {
                    weakself.resultBlack(self.selectedModel);
                    YQPGoodInfoModel *infoModel = weakself.infoModel;
                    weakself.updateGoodsInofBlack(self.infoModel);
                }else{
                    MYShopDetailsSpecificationsAddCountCell *cell = [self.specificationsCollView dequeueReusableCellWithReuseIdentifier:@"MYShopDetailsSpecificationsAddCountCell" forIndexPath:[NSIndexPath indexPathForItem:0 inSection:self.attrArray.count]];
                    YQPSpuSaleAttrValueListModel *model = YQPSpuSaleAttrValueListModel.new;
                    model.ID = self.model.ID;
                    model.buyNumber = cell.numTextFiled.text;
                    weakself.resultBlack(model);
                }
            }
            
            [weakself cancelSelctTableView];
            
        }];
    }
    return _bottonView;
}

#pragma mark -- lazy end
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
